<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>组织管理/下属管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${ctx}/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="${ctx}/systemStatic/style/admin.css">
    <link rel="stylesheet" href="${ctx}/extends/zTree_v3/css/zTreeStyle/zTreeStyle.css"/>
    <link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>
    <link rel="stylesheet" href="${ctx}/css/public.css">
    <script type="text/javascript">
        var __ctx = "${ctx}";
    </script>
</head>
<body>
<table id="managementOfSub" lay-filter="managementOfSub"></table>
    <div class="layui-form-item">
        <div class="layui-input-block" style="text-align: center;margin:0;margin-top: 15px">
            <a  class="layui-btn cancelMent layui-btn-danger">取消</a>
        </div>
    </div>
    <script type="text/html" id="headermanagement">
        <div class="ccpui-enterSel">
        <div class="layui-btn-container">
            <a class="layui-btn layui-btn-sm" lay-event="add">
                <i class="layui-icon layui-icon-add-1"></i>
                <span>新增</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="delete">
                <i class="layui-icon layui-icon-delete"></i>
                <span>删除</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="query">
                <i class="layui-icon layui-icon-search"></i>
                <span>查询</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="clears">
                <i class="layui-icon layui-icon-refresh-3"></i>
                <span>重置</span>
            </a>
        </div>
        <form class="layui-form" action="" lay-filter="headManagement" style="margin-top:10px" onsubmit="return false">
            <div class="table-top-filter">
                <div class="table-filter-alone">
                    <label class="layui-form-label">姓名</label>
                    <input style="width:180px" type="text" class="layui-input  filter-value" name="Q_underUserName_SL" />
                </div>
            </div>
        </form>
        </div>
    </script>
    <script type="text/html" id="headermanagementUser">
        <div class="layui-btn-container" >
            <a class="layui-btn layui-btn-sm" lay-event="query">
                <i class="layui-icon layui-icon-search"></i>
                <span>查询</span>
            </a>
        </div>
        <form class="layui-form" action="" lay-filter="headManagementUser" style="margin-top:10px">
            <div class="table-top-filter">
                <div class="table-filter-alone">
                    <label class="layui-form-label">姓名</label>
                    <input style="width:180px" type="text" class="layui-input filter-value" name="Q_fullName_SL" />
                </div>
            </div>
        </form>
    </script>
    <div name="userSelectorOne" style="overflow: hidden;display: none" hidden >
        <div class="ccpui-leftTree">
            <span style="background: #e6e6e6;width: 100%;height: 30px;line-height: 30px;padding-left:12px;display: inline-block;">按组织查找</span>
            <ul id="treeSelectUsers" class="ztree ccpui-selector"></ul>
        </div>
        <div class="ccpui-centerTree">
            <div class="filter-table" style="position: relative;">
                <table class="layui-hide" id="userselectorAdds" lay-filter="userselectorAdds"></table>
                <div style="height: 520px;overflow: auto;position:absolute;right:-30px;top:-10px;width:30%">
                    <table class="layui-table" id="UserApps">
                        <thead>
                        <tr>
                            <th>已选择</th>
                        </tr>
                        </thead>
                        <tbody class="contentDiv">
                        <tr>
                            <td></td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="bottom" style="position: absolute;bottom:15px;left:375px;z-index: 666">
            <button class="layui-btn saveData" >保存</button>
            <button class="layui-btn cancelData" >撤销</button>
            <button class="layui-btn  layui-btn-danger cancelDatas" >取消</button>
        </div>
    </div>
    <script type="text/html" id="rightToolsBarManage">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
<script src="${ctx}/extends/jquery.min.js" type="text/javascript"></script>
<script src="${ctx}/public/component.js" type="text/javascript"></script>
<script src="${ctx}/layui/layui.js"></script>
<script src="${ctx}/extends/zTree_v3/js/jquery.ztree.all.min.js" type="text/javascript"></script>
<script src="${ctx}/extends/zTree_v3/js/jquery.ztree.exhide.min.js" type="text/javascript"></script>
<script>
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','table', 'layer', 'treeSelect', 'form', 'laydate', 'totalFilter','setter','commons','common'], function () {
            var table = layui.table,layer = layui.layer,form = layui.form,$ = layui.jquery,totalFilter = layui.totalFilter;
            var setter=layui.setter,commons=layui.commons,common=layui.common;
            var indexUserSel;//用户选择器弹窗   index
            var userList=[];//数据初始获取全局数组
            var superConfigDatas=[];//下属管理   json数组
            var userId = '${userId}';

            table.render({
                elem: '#managementOfSub',
                cellMinWidth: 80,
                height: 'full-75',
                url: serverPath.systemPath + setter.sysLinkPath+'userUnder/queryUnderByUserId', //数据接口
                page: true, //开启分页
                method: 'get',
                toolbar: '#headermanagement',
                defaultToolbar: ['filter', 'print'],
                where: {userId:userId},
                cols: [
                    [
                        {type: 'checkbox',},
                        {field: 'underUserId', title: 'ID', sort: true, hide: true},
                        {field: 'underUserName', align: 'center', title: '下属用户名', sort: true},
                        {fixed: 'right', width: 200, align: 'center', title: '管理', toolbar: '#rightToolsBarManage'}
                    ]
                ],done:function () {
                    common.tableSelectCon('.ccpui-enterSel .layui-form input','a[lay-event=query]','.ccpui-enterSel')
                }
            });
            totalFilter.init('managementOfSub');
            table.on('toolbar(managementOfSub)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data;
                switch (obj.event) {
                    case 'add':
                         indexUserSel=layer.open({
                            type: 1,
                            area: ['980px', '580px'],
                            resize:false,
                            title: ['用户选择器'],
                            content: $("[name='userSelectorOne']"),
                            success:function () {
                                $.ajax({
                                    url: serverPath.systemPath + setter.sysLinkPath+'userUnder/queryUnderByUserId',
                                    type: "get",
                                    dataType: 'json',
                                    data: {
                                        needPage: "0",
                                        userId:userId
                                    },
                                    success: function (data) {
                                        if (commons._filterRecord(data)) {
                                            var userManage=[];
                                            for (var i = 0; i < data.data.length; i++) {
                                                userManage.push({
                                                    name: data.data[i].underUserName,
                                                    userId: data.data[i].underUserId
                                                });
                                            }
                                            userList=userManage;
                                            table.reload("userselectorAdds", {
                                                parseData: function (res) {
                                                    var _data = res.data;
                                                    if (_data.length > 0 && userList.length > 0) {
                                                        for (var i = 0; i < _data.length; i++) {
                                                            var _d = _data[i];
                                                            for (var j = 0; j < userList.length; j++) {
                                                                var _td = userList[j];
                                                                if (_d.userId === _td.userId) {
                                                                    _d.LAY_CHECKED = true;
                                                                }
                                                            }
                                                        }
                                                    }
                                                },
                                                page: {curr: 1}
                                            });
                                            $(".contentDiv").html("");
                                            for (var i = 0; i < userList.length; i++) {
                                                $(".contentDiv").append("<tr><td>" +"<span>" +userList[i].name +"</span>"+ " <i selectIds="+"'"+userList[i].userId+"'"+
                                                    "class='layui-icon' style='position:absolute;right:12px;cursor: pointer'>&#xe640;</i></td></tr>");
                                            }
                                        } else {
                                            window.parent.layer.alert(data.msg);
                                        }
                                    }
                                })
                            }
                        });
                        break;
                    case 'delete':
                        if (data.length === 0) {
                            layer.msg('请先选择一行数据！');
                        } else {
                            var seleIds = [];
                            for (var i = 0; i < data.length; i++) {
                                seleIds.push(data[i].id);
                            }
                            layer.confirm('确定删除当前数据吗？', function (index) {
                                layer.close(index);
                                $.ajax({
                                    url: serverPath.systemPath + setter.sysLinkPath+"userUnder/del",
                                    type: "get",
                                    contentType: 'application/json',
                                    dataType: 'json',
                                    data: {id:seleIds.join(","),},
                                    success: function (data) {
                                        if (commons._filterRecord(data)) {
                                            table.reload('managementOfSub', {page: {curr: 1,},});
                                        } else {
                                            layer.alert(data.msg);
                                        }
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                                    },
                                })
                            })
                        }
                        break;
                    case 'query':
                        common.tableConditionRender("managementOfSub","headManagement",{where:{}},false);
                        break;
                    case 'clears':
                        common.tableConditionRender("managementOfSub","headManagement",{where:{}},true);
                }
            });
            table.on('tool(managementOfSub)', function (obj) {
                var data = obj.data, //获得当前行数据
                    layEvent = obj.event; //获得 lay-event 对应的值
                switch (layEvent) {
                    case 'del':
                    layer.confirm('确定删除当前数据吗？', function (index) {
                        layer.close(index);
                        var seleId = obj.data.id;
                        $.ajax({
                            url: serverPath.systemPath + setter.sysLinkPath+"userUnder/del",
                            type: "get",
                            contentType: 'application/json',
                            dataType: 'json',
                            data: {id:seleId},
                            success: function (data) {
                                if (commons._filterRecord(data)) {
                                    table.reload('managementOfSub', {page: {curr: 1,},});
                                } else {
                                    layer.alert(data.msg);
                                }
                            },
                        })
                    });
                }
            });

            orgHigherLevels();
            function orgHigherLevels() {
                $.ajax({
                    url: serverPath.systemPath + setter.sysLinkPath + "sysOrg/list",
                    type: "get",
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (data) {
                        if (commons._filterRecord(data)) {
                            var zNodes = data.data;
                            var setting = {
                                view: {
                                    showLine: false,
                                    nameIsHTML: true
                                },
                                data: {
                                    simpleData: {
                                        enable: true,
                                        idKey:"orgId",
                                        pIdKey:"orgSupId"
                                    }
                                },
                                callback: {
                                    onClick: onClickOrgUser,
                                }
                            };
                            $.fn.zTree.init($('#treeSelectUsers'), setting, zNodes);
                        } else {
                            layer.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                    },
                });
            }

            function onClickOrgUser(event, treeId, treeNode, clickFlag) {
                selectOrgId = treeNode.orgId;
                common.tableConditionRender("userselectorAdds","headManagementUser",{where:{"orgId":treeNode.orgId}},true);
            }

            table.render({
                elem: '#userselectorAdds',
                method: 'get',
                url: serverPath.systemPath + setter.sysLinkPath + 'sysUser/list',
                page: true,
                height: 'full-144',
                where: {},
                defaultToolbar: ['filter', 'print'],
                toolbar:'#headermanagementUser',
                cols: [
                    [
                        {type: 'checkbox'},
                        {field: 'userId', title: 'ID', sort: true, hide: true},
                        {field: 'fullName', title: '姓名', width: 210,sort: true},
                        {field: 'orgName', width: 210, title: '所属组织',sort: true}
                    ]
                ],
                done: function (data) {
                }
            });
            table.on('toolbar(userselectorAdds)', function (obj) {
                switch (obj.event) {
                    case 'query':
                        common.tableConditionRender("userselectorAdds","headManagementUser",{where:{}},false);
                        break;
                }
            });

            $(document).on("click",".layui-table-body table.layui-table tbody tr",function(){
                var obj = event ? event.target : event.srcElement;
                var tag = obj.tagName;
                var checkbox = $(this).find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
                if(checkbox.length!=0){
                    if(tag == 'DIV') {
                        checkbox.click();
                    }
                }
            });
            $(document).on("click","td div.laytable-cell-checkbox div.layui-form-checkbox",function(e){
                e.stopPropagation();
            });
            table.on('checkbox(userselectorAdds)', function (obj) {
                var data = obj.data;
                var sel = obj.checked; //复选框状态
                var allS = obj.type; //是否全选
                var msg = {
                    name: data.fullName,
                    userId: data.userId
                } //选中行的name值
                var arr_re = JSON.stringify(userList).indexOf(JSON.stringify(msg)); //判断有没有
                var arrAll = table.cache.userselectorAdds;
                var inxdex = 0;
                //全选
                if (allS == 'all') {
                    if (sel) {
                        for (var i = 0; i < arrAll.length; i++) {
                            var msgs = {
                                name: arrAll[i].fullName,
                                userId: arrAll[i].userId
                            }
                            var arr_res = JSON.stringify(userList).indexOf(JSON.stringify(msgs));
                            if (arr_res == -1) {
                                userList.push(msgs)
                            }
                        }
                    } else {
                        for (var i = 0; i < userList.length; i++) {
                            for (var j = 0; j < arrAll.length; j++) {
                                if (userList[i].userId == arrAll[j].userId) {
                                    userList.splice(i, 1);
                                    i--;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    if (sel) {
                        if (arr_re == -1) {
                            userList.push(msg);
                        }
                    } else {
                        if (arr_re != -1) {
                            for (var i = 0; i < userList.length; i++) {
                                if (userList[i].userId == msg.userId) {
                                    index = i;
                                }
                            }
                            userList.splice(index, 1);
                        }
                    }
                }
                $(".contentDiv").html("");
                superConfigDatas=[];
                for (var i = 0; i < userList.length; i++) {
                    $(".contentDiv").append("<tr><td>" +"<span>" +userList[i].name +"</span>"+ " <i selectIds="+"'"+userList[i].userId+"'"
                        + "class='layui-icon' style='position:absolute;right:12px;cursor: pointer'>&#xe640;</i></td></tr>");
                    superConfigDatas.push(userList[i].userId);
                }
                $(".contentDiv .layui-icon").click(function () {
                    $(this).parent().parent().remove();
                    var delData=$(this).attr('selectIds');
                    for (var i = 0; i < userList.length; i++) {
                        if(userList[i].userId==delData){
                            userList.splice(i, 1);
                        }
                    }
                    table.reload("userselectorAdds", {
                        parseData: function (res) {
                            var _data = res.data;
                            if (_data.length > 0 && userList.length > 0) {
                                for (var i = 0; i < _data.length; i++) {
                                    var _d = _data[i];
                                    for (var j = 0; j < userList.length; j++) {
                                        var _td = userList[j];
                                        if (_d.userId === _td.userId) {
                                            _d.LAY_CHECKED = true;
                                        }
                                    }
                                }
                            }
                        },
                        page: {curr: 1}
                    });
                })

            });
            //全部取消
            $(".bottom .cancelData").click(function () {
                $(".contentDiv").html("");
                userList = [];
                table.reload('userselectorAdds');
            });
            //取消
            $(".bottom .cancelDatas").click(function () {
                layer.close(indexUserSel);
            });
            //保存
            $(".bottom .saveData").click(function () {
                $.ajax({
                    url: serverPath.systemPath + setter.sysLinkPath + "userUnder/batchAddUserUnder",
                    type: "get",
                    contentType: 'application/json',
                    dataType: 'json',
                    data:{
                        userUnderId:  superConfigDatas.join(','),
                        userId:userId
                    },
                    success: function (data) {
                        if (commons._filterRecord(data)) {
                            table.reload('managementOfSub') ;
                            $(".contentDiv").html("");
                            userList = [];
                            superConfigDatas = userList;
                            layer.close(indexUserSel);
                        } else {
                           layer.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                    },
                });
            });
            $(".cancelMent").click(function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });
        })
    </script>
</body>
</html>